package com.happy_lab_management.demo.technician.equipmentRepair.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happy_lab_management.context.BaseContext;
import com.happy_lab_management.demo.admin.user.service.TeacherService;
import com.happy_lab_management.demo.admin.user.service.TechnicianService;
import com.happy_lab_management.demo.teacher.equipmentRepair.service.EquipmentRepairService;
import com.happy_lab_management.demo.technician.lab.service.LabService;
import com.happy_lab_management.entity.*;
import com.happy_lab_management.entity.VO.EquipmentRepairVO;
import com.happy_lab_management.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController("technicianEquipRepair")
@RequestMapping("/technician/equipRepair")
@Slf4j
public class EquipmentRepairController {
    @Autowired
    private EquipmentRepairService equipmentRepairService;
    @Autowired
    private TechnicianService technicianService;
    @Autowired
    private LabService labService;
    @Autowired
    private TeacherService teacherService;

    /**
     * 分页查询列出当前实验员管理的报修
     *
     * @return
     */
    @PostMapping("/list")
    public Result<IPage<EquipmentRepairVO>> list(@RequestParam(required = false) String teacherName,
                                                 @RequestParam(required = false) String labNumber,
                                                 @RequestParam(required = false) String status,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        Integer userId = BaseContext.getCurrentId();
        Technician technician = technicianService.selectByUserId(userId);
        List<Lab> labs = labService.selectByTechnicianId(technician.getId());

        QueryWrapper<EquipmentRepair> queryWrapper = new QueryWrapper<>();

        if (!labs.isEmpty()) {
            List<Integer> labIds = labs.stream().map(Lab::getId).collect(Collectors.toList());
            queryWrapper.in("lab_id", labIds);
        } else {
            return Result.success(new Page<EquipmentRepairVO>());
        }

        // 添加基于教师名称、实验室编号和状态的搜索条件
        if (teacherName != null && !teacherName.isEmpty()) {
            List<Integer> teacherIds = teacherService.list(new QueryWrapper<Teacher>().like("name", teacherName))
                    .stream().map(Teacher::getId).collect(Collectors.toList());
            queryWrapper.in("teacher_id", teacherIds);
        }

        if (labNumber != null && !labNumber.isEmpty()) {
            List<Integer> labIds = labService.list(new QueryWrapper<Lab>().like("lab_number", labNumber))
                    .stream().map(Lab::getId).collect(Collectors.toList());
            queryWrapper.in("lab_id", labIds);
        }

        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }


        Page<EquipmentRepair> page = new Page<>(pageNo, pageSize);
        IPage<EquipmentRepair> pageList = equipmentRepairService.page(page, queryWrapper);

        List<EquipmentRepairVO> vos = pageList.getRecords().stream().map(er -> {
            EquipmentRepairVO vo = new EquipmentRepairVO();
            vo.setId(er.getId());
            vo.setStatus(er.getStatus());
            vo.setRepairDate(er.getRepairDate());
            vo.setApplicationDescription(er.getApplicationDescription());
            vo.setTeacherName(teacherService.getById(er.getTeacherId()).getName());
            vo.setLabNumber(labService.getById(er.getLabId()).getLabNumber());
            vo.setCompletionDescription(er.getCompletionDescription());
            return vo;
        }).collect(Collectors.toList());
        Page<EquipmentRepairVO> voPage = new Page<>();
        voPage.setRecords(vos);
        voPage.setTotal(pageList.getTotal());
        voPage.setSize(pageList.getSize());
        voPage.setCurrent(pageList.getCurrent());
        return Result.success(voPage);
    }


    /**
     * 设置维修状态
     * @param id 报修单ID
     * @param status 维修状态（可选参数）
     * @param completionDescription 完成描述（仅当状态为已维修时传递）
     * @return 返回操作结果
     */
    @PostMapping("/updateStatus")
    public Result<String> updateRepairStatus(
            @RequestParam Integer id,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String completionDescription
    ) {
        EquipmentRepair equipmentRepair = equipmentRepairService.getById(id);

        if (status != null) {
            equipmentRepair.setStatus(status);
            equipmentRepair.setCompletionDescription("");
        }

        if ("已维修".equals(status) && completionDescription != null) {
            equipmentRepair.setCompletionDescription(completionDescription);
        }

        equipmentRepairService.updateById(equipmentRepair);

        return Result.success("设置报修状态成功");
    }



}
